import React from "react";
import {
  Form,
  Modal,
  Table,
  Button,
  Spin,
  Input,
} from "antd";
import { connect } from "dva";
import FlowHandleBaseForm from "./TemplateFlowHandleBaseForm";
import styles from "./MoreBtnForm.less";

const { TextArea, Search } = Input;
const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 },
};

// @Form.create()
@connect(({ FlowHandle }) => ({
  FlowHandleStore: FlowHandle,
}))
class MoreBtnForm extends FlowHandleBaseForm {
  constructor(props) {
    super(props);

    this.checkedKeys = [];
    this.treeRef = "";
    this.state = {
      checkedNodes: [],
      disabled: false,
      noticeUserSelectorVisible: false,
      noticeUsers: [], // 自定添加的通知接收人  { userCode, userName, userOrgDesc },
      addCheckNodeToNoticeUser: false,
      keyWord: '',
      pageNum: 1,
      pageSize: 6,
      totalCount: 0,
      listData: [],
      selectedRowKeys: [],
    };
  }

  componentDidMount() {
    this.noticeKey = '加签';
    this.loadMessageTheme();
  }

  handleOk = () => {
    const {
      form,
      onCancel,
      dispatch,
      title,
      getList,
    } = this.props;

    const { noticeUsers } = this.state;
    const taskId = this.getTaskId();
    const u = sessionStorage.getItem("USER_CODE");

    if (noticeUsers.length === 0) {
      this.openNotificationWithIcon("error", "", `请选择流程${title}人员`);
      return;
    }
    if (noticeUsers.some(v => v.userCode === u) && title === '转办') {
      this.openNotificationWithIcon("error", "", `流程${title}不可选择自己`);
      return;
    }
    if ((noticeUsers.length > 1) && (title === '转办' || title === '委派' || title === '指定后续节点处理人')) {
      this.openNotificationWithIcon("error", "", `流程${title}最多只能选择一人`);
      return;
    }
    form.validateFields((err, values) => {
      if (err) {
        return;
      }

    const renderApi = (titles) => {
      switch (titles) {
        case '指定后续节点处理人':
          return {
            type: "FlowHandle/nextNodeAssignee",
            payload: {
              taskId,
              nextNodeAssignee: noticeUsers && noticeUsers[0].userCode,
              ...values,
            },
          }
          case '委派':
            return {
              type: "FlowHandle/delegateTask",
              payload: {
                taskId,
                delegateUserCode: noticeUsers && noticeUsers[0].userCode,
                delegateUserName: noticeUsers && noticeUsers[0].userName,
                ...values,
              },
            }
            case '加签':
              return {
                type: "FlowHandle/addSignTask",
                payload: {
                  taskId,
                  signPersoneds: noticeUsers.map(({ userCode: _code }) => _code),
                  ...values,
                },
              }
        default:
          return {
            type: "FlowHandle/dispatchWorkItem",
            payload: {
              taskId,
              userCode: sessionStorage.getItem("USER_CODE"),
              turnToUserCode: noticeUsers.map(({ userCode: _code }) => _code).join(),
              ...values,
            },
          }
      }
    }

      dispatch({
        type: renderApi(title).type,
        payload: renderApi(title).payload,
      }).then(({ errCode, errMsg }) => {
        if (errCode === 0) {
          onCancel("moreBtnVisible", false);
          this.openNotificationWithIcon("success", "", `${title}成功`);
          if (getList instanceof Function) {
            getList();
          }
        } else {
          this.openNotificationWithIcon("error", "", errMsg);
        }
      })
    });
  };

  // handleDelete = (record) => {
  //   const { noticeUsers } = this.state;
  //   const newNoticeUsers = noticeUsers.filter((v) => v.userCode !== record.userCode);
  //   this.setState({ noticeUsers: newNoticeUsers });
  // };

  handleChange = e => {
    this.setState({
      keyWord: e,
      selectedRowKeys: [],
      noticeUsers: [],
    }, () => { this.onSearch() })
  }

  changePage = pageNum => {
    this.setState({ pageNum }, () => {
      this.onSearch();
    })
  };

  changePageSize = (_, pageSize) => {
    this.setState({ pageNum: 1, pageSize }, () => { this.onSearch()});
  };

  onSearch = () => {
    const { dispatch } = this.props;
    const { pageNum, pageSize, keyWord } = this.state;
    dispatch({
      type: 'FlowHandle/selectEmployeeList', payload: { employeeName: keyWord, pageIndex: pageNum, pageSize },
    }).then(({ errCode, errMsg, datas }) => {
      if (errCode === 0) {
        this.setState({
          listData: datas.dataList,
          totalCount: datas.total,
        });
      } else {
        this.openNotificationWithIcon('error', '', errMsg || '搜索失败');
      }
    });
  }

  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
    const { FlowHandleStore } = this.props;
    const { listSearchData } = FlowHandleStore;
    const result = [];
    listSearchData.map((item) => {
      if (selectedRowKeys.includes(item.userId)) {
        result.push({ userCode: item.userId, userName: item.employeeName });
      }
      return null;
    })
    this.setState({
      noticeUsers: result,
    })
  };

  render() {
    const { selectedRowKeys, pageNum, pageSize, listData, totalCount } = this.state;
    const { form, onCancel, visible, confirmLoading, title } = this.props;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const columns = [
      {
        title: '用户工号',
        dataIndex: 'employeeCode',
        key: "employeeCode",
      },
      {
        title: "用户姓名",
        dataIndex: "employeeName",
        key: "employeeName",
      },
      {
        title: '所属组织',
        dataIndex: "orgName",
        key: "orgName",
        render: (text, record) => (
         record.orgList.map(item => item.orgName).join("，")
        ),
      },
      // {
      //   title: "操作",
      //   render: (text, record) => {
      //     return (
      //       <a
      //         onClick={(e) => {
      //           e.preventDefault();
      //           this.handleDelete(record);
      //         }}
      //       >
      //         移除
      //       </a>
      //     );
      //   },
      // }
    ];

    const { getFieldDecorator } = form;

    return (
      <Modal
        title={title}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => onCancel("moreBtnVisible", false)}
        width="650px"
        centered
        destroyOnClose
        className={styles.root}
        hideRequiredMark
        labelAlign="left"
        confirmLoading={confirmLoading}
        footer={[
          <Button
            key="ok"
            type="primary"
            onClick={this.handleOk}
            loading={confirmLoading}
          >
            确定
          </Button>,
          <Button key="back" onClick={() => onCancel("moreBtnVisible", false)}>
            取消
          </Button>,
        ]}
      >
        <Spin spinning={confirmLoading}>
          {/* {title !== '减签' && (
            <Button
              type="primary"
              onClick={() => {
                this.setState({ noticeUserSelectorVisible: true });
              }}
              className={styles.selectUser}
            >
              选择用户
            </Button>
          )} */}
          <Search
            style={{ margin: '12px 0', width: 240 }}
            placeholder="请输入用户姓名或者工号"
            onSearch={this.handleChange}
          />
          <Form>
            <Table
              columns={columns}
              size="small"
              rowKey="userId"
              rowSelection={rowSelection}
              dataSource={listData}
              pagination={{
                size: "small",
                showSizeChanger: true,
                showQuickJumper: true,
                onChange: this.changePage,
                onShowSizeChange: this.changePageSize,
                pageSize,
                current: pageNum,
                total: totalCount,
                pageSizeOptions: ["6", "10", "20", "30"],
              }}
              // scroll={{y:300}}
            />
            {/* {this.renderNoticeUsers()} */}
            <div className={styles.opinion}>意见</div>
            <Form.Item label="" {...formItemLayout}>
              {getFieldDecorator("comment", {
                    rules: [
                      { max: 100, message: "请不要超过200个字符" },
                      // { required: true, message: "请输入意见" },
                    ],
                  })(<TextArea placeholder="请输入意见，最大限制在200个字数内" rows={5} />)}
            </Form.Item>
          </Form>
        </Spin>
      </Modal>
    );
  }
}

export { MoreBtnForm as RawAddSignForm };
export default Form.create()(MoreBtnForm);
